package com.binyuan.move.thried;



import com.binyuan.move.config.RecorderConfig;
import com.binyuan.move.config.ThreadConfig;
import com.binyuan.move.domain.ScreenRecorderMove;
import com.binyuan.move.service.IScreenRecorderMoveService;
import com.binyuan.move.utils.FileUtils;
import com.binyuan.move.utils.VideoRecord;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.awt.*;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * 自定义鼠标移动线程
 */
@Component
public class MouseMovementThread implements Runnable {
    Logger logger = LoggerFactory.getLogger(MouseMovementThread.class);

    public final  static String SKIMMING = "\\";
    public final static String YS = "ys";
    private RecorderConfig recorderConfig = null;
    private ThreadConfig threadConfig = null;

    /**
     * 线程状态
     */

    private  boolean running = true;



    /**
     * 录像状态
     */
    private  boolean status  = false;
    /**
     * 录像时长
     */
    private  Long seconds = 0L;


    /**
     * 停止操作时长
     */
    private  Long stops = 0L;
    /**
     * 上次x位置
     */
    private int upX = 0;
    /**
     * 上次y位置
     */
    private int upY  = 0;

    /**
     * 本次录制视频的名称
     */
    String fileName = null;

    String dataTimeName = null;
    /**
     * 录像对象
     */
    VideoRecord videoRecord = null;

    IScreenRecorderMoveService moveService = null;

    public VideoRecord getVideoRecord() {
        return videoRecord;
    }

    public void setVideoRecord(VideoRecord videoRecord) {
        this.videoRecord = videoRecord;
    }
    Runnable task = null;
    ScheduledExecutorService executor = null;


    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    /**
     * 暂停
     */
    public void stop(){
    this.running = false;
    }


    public MouseMovementThread() {

    }


    @Override
    public void run() {

        //获取bean
         recorderConfig = SpringContextUtil.getBean(RecorderConfig.class);
         threadConfig = SpringContextUtil.getBean(ThreadConfig.class);
         moveService   = SpringContextUtil.getBean(IScreenRecorderMoveService.class);

         executor = Executors.newScheduledThreadPool(1);

         task = () -> {
            // 执行你的任务
            try {
                //如果没有文件夹则新建
                String nowDate =  DateUtils.parseDateToStr( DateUtils.YYYY_MM_DD,new Date());
                File holder = new File(recorderConfig.getSaveTo()+SKIMMING+nowDate);
                if (!holder.exists()){
                    holder.mkdirs();
                }

                Point p = MouseInfo.getPointerInfo().getLocation();
                //System.out.println("]鼠标当前位置：x=" + p.x + ", y=" + p.y);
                secendsManager(p.x,p.y
                        ,nowDate);


            }catch (Exception e){
                logger.error("任务线程发生异常"+e.getMessage());
            }
        };

        // 在固定的时间间隔执行任务
        executor.scheduleAtFixedRate(task, 0, threadConfig.getInterval(), TimeUnit.SECONDS);


    }


    /**
     * 录屏核心方法
     * @param x 本次x坐标
     * @param y 本次y坐标
     */
    public void  secendsManager(int x,int y,String nowDate){
        if (x == upX && y == upY){
            logger.info("待机中"+ stops);
            //如果本次等于上次,增加待机时间，
            // 确保待机时间 不得超过100控制大小
            if (stops < threadConfig.getMaxMinSize()){
                stops += threadConfig.getInterval();
            }
            if (stops >= threadConfig.getMaxMinSize() && status){
                //说明停止时间超过最长时间 录屏停止
                seconds = 0L;
                stopMove(nowDate);
            }
        }else {
           logger.info("录制时长s:"+ seconds);
            if (seconds <= 3650){
                seconds += threadConfig.getInterval();
            }
            //logger.info("移动中");
            upX = x;
            upY = y;
            stops = 0L;
            if (!status){
                seconds = 0L;
                startMove(nowDate);
            }else{
                if (seconds  >= threadConfig.getMoveMaxLength()){
                    //一个小时
                    upX = x;
                    upY = y;
                    seconds = 0L;
                    stopMove(nowDate);
                }
            }
        }
    }

    /**
     * 启动录制
     * @param
     * @param
     * @param
     */
    public void startMove(String nowDate){
        logger.info(dataTimeName+"]开始录屏");
         dataTimeName =  DateUtils.parseDateToStr( DateUtils.YYYY_MM_DD_HH_MM_SS,new Date());
        //如果没在运行运行则启动录屏
        fileName = DateUtils.dateTimeNow();
        status =true;
        String fn  = recorderConfig.getSaveTo() +SKIMMING+ nowDate + SKIMMING;
        videoRecord = new VideoRecord(fn + fileName, false);

        videoRecord.start();
        moveService.insertScreenRecorderMove(new ScreenRecorderMove(fn+fileName+".mp4",dataTimeName,1L,null,"12",DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,dataTimeName)));
        logger.info(dataTimeName+"]开始录屏结束");
    }

    /**
     * 停止录制
     * @param date
     * @param
     * @param
     */
    public void  stopMove(String date){
        logger.info(date+"]录屏停止");

      try {
          status = false;
          videoRecord.stop();
          videoRecord = null;
          //压缩
          Thread  compressedThread = new Thread(new CompressThreads(recorderConfig.getSaveTo() + SKIMMING + date+SKIMMING + fileName + ".mp4"
                  ,YS + fileName + ".mp4"));
          compressedThread.start();
          List<ScreenRecorderMove> list =  moveService.selectScreenRecorderMoveList(new ScreenRecorderMove(dataTimeName));
          if (!list.isEmpty()){
              moveService.updateScreenRecorderMove(new ScreenRecorderMove(list.get(0).getMoveId(),2L,new Date()));
          }
          System.gc();
      }catch (Exception e){
          e.printStackTrace();
      }


        logger.info(date+"]录屏停止结束");
    }


    public  void stopThread(){
        String nowDate =  DateUtils.parseDateToStr( DateUtils.YYYY_MM_DD,new Date());
       try {
           stopMove(nowDate);
       }catch (Exception e){
           logger.error("关闭录制出错");
       }
        this.executor.shutdownNow();
        this.executor = null;
        this.task = null;
        this.stop();

    }

}
